package com.sanq.product.cab.interceptors;

import com.sanq.product.cab.redis.constants.BusCode;
import com.sanq.product.cab.enums.SecurityFieldEnum;
import com.sanq.product.cab.exceptions.BusException;
import com.sanq.product.cab.tools.date.LocalDateUtils;
import com.sanq.product.cab.tools.strings.StringUtil;
import com.sanq.product.cab.tools.web.ParamUtils;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * version: 接口拦截验证， 基于 sign 验证方式
 * ---------------------
 *
 * @author sanq.Yan
 * @date 2020/1/26
 */
public abstract class SecurityInterceptor extends BaseInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (handler instanceof HandlerMethod) {

            if (super.preHandle(request, response, handler)) {
                return true;
            }

            Object o = objectMap.get(SecurityFieldEnum.TIMESTAMP.getName());
            if (o == null)
                throw new BusException(String.format("参数%s不存在", SecurityFieldEnum.TIMESTAMP.getName()), BusCode.PARAM_CODE);

            Long timestamp = StringUtil.toLong(o);

            if (LocalDateUtils.nowTime().getTime() - timestamp >= 60 * 1000)
                throw new BusException(String.format("参数%s已过期", SecurityFieldEnum.TIMESTAMP.getName()), BusCode.PARAM_CODE);

            o = objectMap.get(SecurityFieldEnum.SIGN.getName());
            if (o == null)
                throw new BusException(String.format("参数%s不存在", SecurityFieldEnum.SIGN.getName()), BusCode.PARAM_CODE);

            String sign = (String) o;

            String paramsSign = ParamUtils.getInstance().getSign(objectMap);
            if (!sign.equals(paramsSign)) {
                throw new BusException(String.format("参数%s验证不正确", SecurityFieldEnum.SIGN.getName()), BusCode.PARAM_CODE);
            }
            return true;
        }
        return false;
    }

}
